package com.xyht.sca_s.student_manage_system.modules.patrol.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.common.util.TimeUtil;
import com.xyht.sca_s.student_manage_system.modules.common.constant.FileSavePathConstant;
import com.xyht.sca_s.student_manage_system.modules.patrol.entity.SmsPatrolImage;
import com.xyht.sca_s.student_manage_system.modules.patrol.mapper.SmsPatrolImageMapper;
import com.xyht.sca_s.student_manage_system.modules.patrol.service.SmsPatrolImageService;
import com.xyht.sca_s.student_manage_system.modules.patrol.entity.vo.SmsPatrolImageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-04-12
 */
@Service
public class SmsPatrolImageServiceImpl extends ServiceImpl<SmsPatrolImageMapper, SmsPatrolImage> implements SmsPatrolImageService {
    @Resource
    private FileSavePathConstant fileSavePathConstant;
    @Autowired
    SmsPatrolImageMapper smsPatrolImageMapper;
    @Override
    public ResponseResult patrolImageAdd(MultipartFile file, String picType) {
        if (file.isEmpty()) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();

        String fileName = file.getOriginalFilename();

        int size = Math.round(file.getSize() / 1024);
        int sizeMB = Math.round(size / 1024);
        if (sizeMB > fileSavePathConstant.getIMG_UPLOAD_MAX()) {
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        }
        log.debug(fileName + "-->" + size + "KB");
        String[] fileTypeArr = fileName.split("\\.");
        String fileType = fileTypeArr[fileTypeArr.length - 1];

        String timeTemp = new Date().getTime() + "";
        String completePath = filePath + timeTemp + "." + fileType;
        String newFileName = timeTemp + "." + fileType;
        File dest = new File(completePath);
        if (!dest.getParentFile().exists()) { //判断文件父目录是否存在
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest); //保存文件
            Map<String,Object> map = new HashMap<>();
            map.put("oldFileName",fileName);
            map.put("newFileName",newFileName);
            return CommonResult.success(map);
        } catch (MaxUploadSizeExceededException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FILE_SIZE_LIMIT_EXCEEDED);
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return CommonResult.failed(CommonCodeEnum.FAIL);
        }






//        String base64Str = null;
//        try {
//
//            base64Str  =  new BASE64Encoder().encode(file.getBytes());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        SmsPatrolImageVO smsPatrolImageVO = new SmsPatrolImageVO();
//        smsPatrolImageVO.setSmsPic(base64Str);
//        smsPatrolImageVO.setPicType(picType);
//        SmsPatrolImage smsPatrolImage = new SmsPatrolImage();
//        smsPatrolImage.setSmsPic(smsPatrolImageVO.getSmsPic());
//        smsPatrolImage.setPicType(smsPatrolImageVO.getPicType());
//        smsPatrolImageMapper.insert(smsPatrolImage);
//        return CommonResult.success(smsPatrolImage.getId());
    }


    @Override
    public ResponseResult deleteById(SmsPatrolImageVO smsPatrolImageVO) {
        if (isNullOrEmpty(smsPatrolImageVO.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsPatrolImage queryResult = smsPatrolImageMapper.selectById(smsPatrolImageVO.getId());
        if (queryResult == null) {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
        smsPatrolImageMapper.deleteById(smsPatrolImageVO.getId());
        return CommonResult.success();
    }



    @Override
    public ResponseResult update(SmsPatrolImageVO smsPatrolImageVO) {
        if (isNullOrEmpty(smsPatrolImageVO)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsPatrolImage queryResult = smsPatrolImageMapper.selectById(smsPatrolImageVO);
        if (queryResult == null) {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
        SmsPatrolImage smsPatrolImage = new SmsPatrolImage();
        BeanUtils.copyProperties(smsPatrolImageVO, smsPatrolImage);
        smsPatrolImageMapper.updateById(smsPatrolImage);
        return CommonResult.success();

    }
    @Override
    public ResponseResult selectPatrolImageByPicType(String pic_type, Integer pageSize, Integer pageNum, String bg_date, String end_date) {
        Date bgDate = null;
        Date endDate = null;
        if (!isNullOrEmpty(bg_date)) {
            bgDate = TimeUtil.StringtoDate(bg_date);
        }
        if (!isNullOrEmpty(end_date)) {
            endDate = TimeUtil.StringtoDate(end_date);

        }
        QueryWrapper<SmsPatrolImage> queryWrapper = new QueryWrapper<>();
//        queryWrapper.lambda().ge(CarSystemAdd::getCreateTime,bgDate);
//        queryWrapper.lambda().le(CarSystemAdd::getCreateTime,endDate);
        if(isNullOrEmpty(queryWrapper)){
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }
        if (bgDate != null) {
            queryWrapper.lambda().ge(SmsPatrolImage::getCreateTime, bgDate);
        }
        if (endDate != null) {
            queryWrapper.lambda().le(SmsPatrolImage::getCreateTime, endDate);
        }
        if (!isNullOrEmpty(pic_type)) {
            queryWrapper.lambda().like(SmsPatrolImage::getPicType, pic_type);
        }
        List<SmsPatrolImage> list1 = smsPatrolImageMapper.selectList(queryWrapper);
        if(list1.size()==0){
            return null;
        }
        queryWrapper.orderByDesc("create_time");
        Page<SmsPatrolImage> page = new Page<>(pageNum,pageSize);

        smsPatrolImageMapper.selectPage(page,queryWrapper);
        List<SmsPatrolImage> list = page.getRecords();
        int total = (int)page.getTotal();
        return CommonResult.success(list,total);
    }

    @Override
    public ResponseResult selectPatrolImage(String id) {
        if (isNullOrEmpty(id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        SmsPatrolImage smsPatrolImage = smsPatrolImageMapper.selectById(id);
        if (smsPatrolImage == null || smsPatrolImage.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
        }

        return CommonResult.success(smsPatrolImage);
    }

    @Override
    public String showImage(int id) {
        if (isNullOrEmpty(id)) {
            return null;
        }
        SmsPatrolImage smsPatrolImage = smsPatrolImageMapper.selectById(id);
        return smsPatrolImage.getSmsPic();
    }

    @Override
    public ResponseResult downloadFileManagement(String path, HttpServletResponse response) {
        String fileName = "";
        if (path == null || path.equals("")) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        FileInputStream fis = null; //文件输入流
        BufferedInputStream bis = null;
        OutputStream os; //输出流

        String OSName = System.getProperty("os.name");
        String filePath = OSName.toLowerCase().startsWith("win") ? fileSavePathConstant.getFILE_DOWNLOAD_PATH()
                : fileSavePathConstant.getFILE_DOWNLOAD_PATH_LINUX();
        String completePath = filePath + path;

        File file = new File(completePath);
        if (file.getParentFile().exists()) { //判断文件父目录是否存在
            try {
                log.debug("fileName=====" + file.getName());
                response.setContentType("application/force-download");
//                response.setContentType("image/**");
                response.setCharacterEncoding("UTF-8");
                // response.setContentType("application/force-download");
                response.setHeader("Content-Disposition", "attachment;fileName=" + java.net.URLEncoder.encode(file.getName(), "UTF-8"));
//                response.setHeader("Access-Control-Expose-Headers", "file-type,file-name");
                byte[] buffer = new byte[1024];

                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);

                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }

            } catch (FileNotFoundException e) {
                return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            log.debug("----------file download---" + fileName);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return CommonResult.failed(CommonCodeEnum.FAIL);
            }
            return null;
        } else {
            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);


            //        if(isNullOrEmpty(id)){
//            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
//        }
//        String fileName = "";
//        OutputStream os; //输出流
//        ByteArrayOutputStream output = null;
//        try {
//            SmsPatrolImage smsPatrolImage = smsPatrolImageMapper.selectById(id);
//            String img = smsPatrolImage.getSmsPic();
//            os = response.getOutputStream();
//            byte[] imgByte = java.util.Base64.getMimeDecoder().decode(img);
//            output = new ByteArrayOutputStream();//可以捕获内存缓冲区【生成的图片在缓冲区里面】的数据，将数据装换成字节数组  ,输出流的缓冲区的大小会随着数据的不断写入而自动增加  使用toByteArray()  toString()获得生成字节数组的数据
//            output.write(imgByte);
//            output.writeTo(os);
//            output.close();
//        } catch (FileNotFoundException e) {
//            return CommonResult.failed(CommonCodeEnum.DATA_NOT_FOUND);
//        } catch (Exception e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//            return CommonResult.failed(CommonCodeEnum.FAIL);
//        }
//        log.debug("----------file download---" + fileName);
//        try {
//            os.flush();
//            os.close();
//
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//            return CommonResult.failed(CommonCodeEnum.FAIL);
//        }
//        return null;
        }


    }
}
